package dht.table;

import java.util.HashMap;
import java.util.HashSet;

import dht.IDataServerRouteTable;
import dht.entity.NodeInfo;

public class DataServerRouteTableImpl extends ClientRouteTableImpl implements
		IDataServerRouteTable {

	private static final long serialVersionUID = 1L;

	public DataServerRouteTableImpl(NodeInfo masterInfo) {
		super(masterInfo);
	}

	@Override
	public synchronized Object tableClone() {
		DataServerRouteTableImpl m = (DataServerRouteTableImpl) super.clone();
		if (masterInfo != null) {
			m.masterInfo = (NodeInfo) masterInfo.clone();
		}
		if (registedServer != null) {
			m.registedServer = new HashMap<String, NodeInfo>();
			for (String serverId : registedServer.keySet()) {
				m.registedServer.put(serverId, registedServer.get(serverId));
			}
		}
		if (vnodeId2ServerIds != null) {
			m.vnodeId2ServerIds = new HashMap<Integer, HashSet<String>>();
			for (Integer vnodeId : vnodeId2ServerIds.keySet()) {
				HashSet<String> serverIds = vnodeId2ServerIds.get(vnodeId);
				if (serverIds != null) {
					HashSet<String> newServerIds = new HashSet<String>();
					for (String serverId : serverIds) {
						newServerIds.add(serverId);
					}
					m.vnodeId2ServerIds.put(vnodeId, newServerIds);
				} else {
					m.vnodeId2ServerIds.put(vnodeId, null);
				}
			}
		}
		return m;
	}

	@Override
	public boolean isInLocal(String fileName, NodeInfo localServerInfo) {
		int vnodeId = getVnodeId(fileName);
		HashSet<String> serverIdList = vnodeId2ServerIds.get(vnodeId);
		if (serverIdList.contains(localServerInfo.getServerId())) {
			return true;
		}
		return false;
	}

}
